package com.zhhh.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.engine.transaction.jta.platform.internal.JOnASJtaPlatform;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.alibaba.fastjson.JSONObject;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import com.zhhh.config.ResultStatus;
import com.zhhh.domain.FilePath;
import com.zhhh.model.ResultModel;
import com.zhhh.repository.FilePathRepository;
import com.zhhh.utils.DocConverter;

@WebServlet(name = "HelloSpringBootServlet", value = "/upload") // 替代web.xml的配置
public class DocUploadConvertServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	

	@Autowired
	private FilePathRepository filePathRepository;

	/**
	 * 再servlet用@Autowired
	 * 注入service参数，会报空指针，注入的bean找不到。这是因为我们的bean都是归spring容器管理的，但是servlet单独有一个容器，归tomcat管理，所以这样注入是有问题的
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());

	}

	@SuppressWarnings("rawtypes")
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
		String saveDirectory = request.getServletContext().getRealPath("/");
		int maxPostSize = 50 * 1024 * 1024;
		DefaultFileRenamePolicy dfp = new DefaultFileRenamePolicy();
		MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize, "UTF-8", dfp);
		Enumeration files = multi.getFileNames();
		while (files.hasMoreElements()) {
			String name = (String) files.nextElement();
			File f = multi.getFile(name);
			if (f != null) {
				String fileName = multi.getFilesystemName(name);
				// 获取上传文件的扩展名
				String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
				// 文件全路径
				String lastFileName = saveDirectory + fileName;
				// 获取需要转换的文件名,将路径名中的'\'替换为'/'
				String converfilename = saveDirectory.replaceAll("\\\\", "/") + "/" + fileName;
				// 调用转换类DocConverter,并将需要转换的文件传递给该类的构造方法
				DocConverter d = new DocConverter(converfilename);
				// 调用conver方法开始转换，先执行doc2pdf()将office文件转换为pdf;再执行pdf2swf()将pdf转换为swf;
				// d.conver();
				String resultJson = "";
				if (d.conver()) {
					// 调用getswfPath()方法，打印转换后的swf文件路径
					// 生成swf相对路径，以便传递给flexpaper播放器
					String pdfPath = d.getPdfPath();
					// 将相对路径放入sessio中保存2323
					String pdfFileName = pdfPath.substring(d.getPdfPath().lastIndexOf("/") + 1,
							d.getPdfPath().length());
					FilePath biaopath = new FilePath();
					//System.out.println(fileName);
					biaopath.setFileName(fileName);
					biaopath.setPath("http://localhost:8080/" + fileName);
					biaopath.setPdfPath(
							"http://localhost:8080/" + fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf");
					filePathRepository.save(biaopath);
					List<FilePath> findAll = (List<FilePath>) filePathRepository.findAll();
					resultJson = JSONObject.toJSONString(ResultModel.ok(findAll));
				}else {
					resultJson = JSONObject.toJSONString(ResultModel.error(ResultStatus.FILE_CONVERSION_ERROR));
				}

				resp.setHeader("Content-Type", "application/json;charset=UTF-8");
				PrintWriter out = resp.getWriter();
				out.print(resultJson);
				out.close();
			}
		}
	}

}
